#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from rest_framework import serializers
import json
from my_rest.exceptions import ServiceUnavilable,ParmError,InnerError
import traceback
from rest_framework.utils.serializer_helpers import ReturnDict

from repository import models
from core.tasks import stock_tasks


class OverviewSerializer(serializers.ModelSerializer):
    """格式化overview字段"""
    filter_fields = ()   # 默认从后端获取哪些字段
    lastOperator = serializers.SerializerMethodField()    # 添加自定义字段用
    lastUpdate = serializers.SerializerMethodField()

    class Meta:
        model = models.StockInfo
        fields = ('id','code','name','stock','threshold','unit','lastOperator','lastUpdate')    # 定义返回给前端时的字段名



    def get_lastOperator(self,stock):
        """
        Args:
            stock: 列表中的每个stock字典

        """
        return stock.get('lastOperator')

    def get_lastUpdate(self,stock):
        """
        Args:
            stock: 列表中的每个stock字典

        """
        return stock.get('lastUpdate')


class OperationOrderSerializer(serializers.Serializer):
    """operation_record相关操作"""
    id = serializers.IntegerField(read_only=True)
    operation_type = serializers.CharField()
    memo = serializers.CharField()
    count = serializers.IntegerField()
    stock_id = serializers.IntegerField(write_only=True)
    operator_id = serializers.IntegerField(read_only=True)

    # 转换字段名用
    type = serializers.SerializerMethodField()
    createdAt = serializers.SerializerMethodField()
    unit = serializers.SerializerMethodField()
    operatorName = serializers.SerializerMethodField()

    # 默认从后端获取哪些字段
    filter_fields = (
        'id','created_at', 'count', 'stock__unit', 'operation_type', 'operator__username', 'memo')

    # 返回给前端哪些字段
    front_fields = ('createdAt', 'count','type','memo', 'unit','operatorName')

    def filter_front_fields(self,ret):
        """过滤多余的字段"""
        for key in list(ret.keys()):
            if key not in self.front_fields:
                ret.pop(key)
        return ret

    def get_type(self,record):
        return record.get('operation_type')

    def get_createdAt(self,record):
        return record.get('created_at')

    def get_unit(self,record):
        return record.get('stock__unit')

    def get_operatorName(self,record):
        return record.get('operator__username')

    @property
    def data(self):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(OperationOrderSerializer, self).data)
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(OperationOrderSerializer, self).to_representation(instance))
        return ret

    def create(self, validated_data):
        '''新增记录'''
        task_res = json.loads(stock_tasks.save_operation_record(instance=None,filter_fields=self.filter_fields,**validated_data))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出

    def validate(self, attrs):
        """自定义验证规则，出货数量不能大于库存数量"""
        res = json.loads(stock_tasks.get_stock_info(id=attrs.get('stock_id')))
        if res['status'] != 200:
            raise InnerError(res['detail'])
        if not res['data']:
            raise serializers.ValidationError('该库存不存在')
        if attrs.get('operation_type') == '2':    # 出货
            stock = res['data']['stock']
            if attrs.get('count')> stock:
                msg = '出库数量不能大于库存'
                raise serializers.ValidationError(msg)
        return attrs


class StockInfoSerializer(serializers.Serializer):
    """stock_info表相关操作"""
    id = serializers.IntegerField(read_only=True)
    code = serializers.CharField()
    name = serializers.CharField()
    stock = serializers.IntegerField()
    threshold = serializers.IntegerField()
    unit = serializers.CharField()

    # 默认从后端获取哪些字段,空表示全部
    filter_fields = ()

    # 返回给前端哪些字段
    front_fields = ('id', 'code','name','stock', 'threshold','unit')

    def filter_front_fields(self,ret):
        """过滤多余的字段"""
        for key in list(ret.keys()):
            if key not in self.front_fields:
                ret.pop(key)
        return ret

    @property
    def data(self):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(StockInfoSerializer, self).data)
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        """过滤多余字段"""
        ret = self.filter_front_fields(super(StockInfoSerializer, self).to_representation(instance))
        return ret

    def validate(self, attrs):    # 判断零件编号是否重复
        code = attrs.get('code')
        if self.instance:
            task_res = json.loads(stock_tasks.if_stock_duplicate(pk=self.instance['id'],code=code))
        else:
            task_res = json.loads(stock_tasks.get_stock_info(code=code))
        if task_res['status'] != 200:
            raise InnerError(task_res['detail'])
        if task_res['data']:
            raise serializers.ValidationError('零件编号不能重复')
        return attrs


    def create(self, validated_data):
        '''新增库存'''
        task_res = json.loads(stock_tasks.save_stock_info(instance=None,*self.filter_fields,**validated_data))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出

    def update(self, instance, validated_data):
        """更改库存"""
        operator_id = validated_data.get('operator_id')
        tmp_instance = {'operator_id':operator_id}
        for key in instance:
            tmp_instance[key] = validated_data.get(key, instance[key])

        task_res = json.loads(stock_tasks.save_stock_info(instance=instance,*self.filter_fields,**tmp_instance))
        if task_res['status'] == 200:
            return task_res['data']
        else:
            raise InnerError(task_res['detail'])    # 如果model层出错，直接抛出



    # def update(self, instance, validated_data):
    #     """修改记录"""
    #     tmp_instance = {'owner_id':validated_data['owner_id']}
    #     for key in instance:
    #         tmp_instance[key] = validated_data.get(key,instance[key])
    #
    #     t = article_tasks.save_article.delay(instance=tmp_instance,filter_fields=self.filter_fields)
    #     try:
    #         new_instance = json.loads(t.get(timeout=10))
    #     except TimeoutError:
    #         raise ServiceUnavilable()
    #
    #     return new_instance










